//
//  XMNewPersonInfoViewController.m
//  XiaoMiao
//
//  Created by Jim huang on 2018/4/29.
//  Copyright © 2018年 smallyou. All rights reserved.
//

#import "XMNewPersonInfoViewController.h"
#import "AddressProvinceCityController.h"

//view
#import "KTiltleAndInputTableViewCell.h"
#import "XMUserDetailInfoMultiSelectTableViewCell.h"
#import "XMSurgeryDetailTableViewCell.h"
#import "XMRemarkTableViewCell.h"
#import "XMTypeListViewController.h"
#import "BRStringPickerView.h"
#import "XMPersonInfoAvatarTableViewCell.h"
#import "XMTitleAlterView.h"

//model
#import "XMUserCreateModel.h"
#import "XMTypeListModel.h"


//other
#import "TZImagePickerController.h"
#import "TZImageManager.h"

#define NUMBERS @"0123456789"
@interface XMNewPersonInfoViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UIAlertViewDelegate>

//列表数据
@property (nonatomic,strong) NSArray  * ListData;
//头部标题
@property (nonatomic,strong) NSArray  * ListHeader;
//列表占位字
@property (nonatomic,strong) NSArray  * ListPlaceHolder;
//医美史
@property (nonatomic,strong) NSArray  * SurgeryDetailArr;
//姓名
@property (nonatomic,strong)UITextField * namTextField;
//性别
@property (nonatomic,strong)UITextField * sexTextField;
//年龄
@property (nonatomic,strong)UITextField * ageTextField;
//手机号
@property (nonatomic,strong)UITextField * phoneTextField;
//城市
@property (nonatomic,strong)UITextField * cityTextField;
//过敏药物
@property (nonatomic,strong)UITextField * medicinalTextField;
//过敏食物
@property (nonatomic,strong)UITextField * foodTextField;
//备注
@property (nonatomic,strong)UITextView * remarkTextView;
//详细地址
@property (nonatomic,strong)UITextView * detailAddressTextView;
//省份
@property (nonatomic,copy) NSString *province;
//城市
@property (nonatomic,copy) NSString *city;
//
@property (nonatomic,strong) XMNewPersonDetailModel *listModel;

@property (nonatomic,strong) UIImagePickerController *imagePicker;
@end

@implementation XMNewPersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem * saveItem = [UIBarButtonItem app_createItemTitle:@"保存" target:self action:@selector(uploadUserDetail)];
    saveItem.tintColor = kMainBlueColor;
    
        UIBarButtonItem * deleteItem = [UIBarButtonItem app_createItemTitle:@"删除" target:self action:@selector(deleteUserDetail)];
    deleteItem.tintColor = HEX_RGB(0xfd5d5d);
    
    self.navigationItem.rightBarButtonItems = @[saveItem,deleteItem];
    self.title = @"编辑个人资料";
    
    //列表数据
    self.ListData = @[@[@"头像"],@[@"姓名",@"性别",@"年龄",@"手机号",@"所在地",@"详细地址"],@[@"既往病史"],@[@"生理状况"],@[@"医美史"],@[@"药物",@"食物"],@[@"其他"]];
    //头部标题
    self.ListHeader = @[@"",@"",@"既往病史",@"生理状况",@"医美史",@"过敏病史",@"其他"];
    
    //列表占位字
    self.ListPlaceHolder = @[@[@""],@[@"",@"",@"如1970",@"请输入手机号码",@"请选择",@"请填写详细地址"],@[@""],@[@""],@[@"请添加医美史"],@[@"请输入过敏药物",@"请输入过敏食物"],@[@"请输入其他备注"]];
    
    self.tableView.refreshEnable = NO;
    self.tableView.loadmoreEnable = NO;
    [self getUserDetail];
    
}


#pragma mark ----tableView----

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.ListData.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray * listArr = self.ListData[section];
    return listArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1 || indexPath.section == 5) {
        if (indexPath.row == 5) {
            return 100;

        }else{
            return 50;
            }
        
    }else if(indexPath.section == 2 || indexPath.section == 3){
        return 120;
        
    }else if(indexPath.section == 4){
        
        if (self.SurgeryDetailArr||self.listModel.partyExtrView.hasSurgeryDetail) {
            
            return 130;
            
        }else{
            return 50;
            
        }
        
    }else{
        return 100;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = kBgColor;
    
    UILabel * titleLabel = [[UILabel alloc]init];
    titleLabel.font = kFont(14);
    titleLabel.textColor = HEX_RGB(0x8d919c);
    [view addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view).offset(15);
    }];
    
    NSString * titleStr = self.ListHeader[section];
    
    titleLabel.text = titleStr;
    
    return view;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //标题
    NSArray * titleArr = self.ListData[indexPath.section];
    NSString * titleStr = titleArr[indexPath.row];
    
    //占位字
    NSArray * placeHolderArr = self.ListPlaceHolder[indexPath.section];
    NSString * placeHolderStr = placeHolderArr[indexPath.row];
    
    //头像
    if (indexPath.section == 0) {
        
        XMPersonInfoAvatarTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMPersonInfoAvatarTableViewCell className]];
        
        if (!cell) {
            cell = [[XMPersonInfoAvatarTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMPersonInfoAvatarTableViewCell className]];
        }
        
        cell.imgUrl = self.listModel.profile;
        return cell;
        
    }else if (indexPath.section == 1 || indexPath.section == 5) {
        //手机 年龄 详细地址 过敏食物 过敏药物
        //详细地址
        if (indexPath.section == 1 && indexPath.row == 5) {
            
            XMRemarkTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMRemarkTableViewCell className]];
            
            if (!cell) {
                cell = [[XMRemarkTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMRemarkTableViewCell className]];
            }
            //详细地址
            cell.placeHolderLabel.text = @"请输入详细地址";
            cell.remarkTextView.text = self.listModel.addr;
            cell.remarkTextView.textColor = kTextGrayColor;
            if (self.listModel.addr.length>0) {
                cell.placeHolderLabel.hidden = YES;
            }else{
                cell.placeHolderLabel.hidden = NO;
            }
            self.detailAddressTextView = cell.remarkTextView;
            MJWeakSelf
            [cell setTextChangeBlock:^(NSString *text) {
                weakSelf.listModel.addr = text;

            }];
            return cell;
        }else{

            NSString * reuseID = [NSString stringWithFormat:@"KTiltleAndInputTableViewCell%li%li",(long)indexPath.section,(long)indexPath.row];
            KTiltleAndInputTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
            
            if (!cell) {
                cell = [[KTiltleAndInputTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            
            cell.titleLabel.text = titleStr;
            cell.inputTextField.placeholder = placeHolderStr;
            cell.inputTextField.textColor = kTextGrayColor;
            cell.inputTextField.userInteractionEnabled = YES;

            if (indexPath.section == 1) {
                cell.accessoryType = UITableViewCellAccessoryNone;
                cell.inputTextField.userInteractionEnabled = YES;
                cell.inputTextField.textAlignment = NSTextAlignmentRight;


                if (indexPath.row == 0) {
                    //真实姓名
                    cell.inputTextField.text = self.listModel.realName;
                    self.namTextField = cell.inputTextField;
                    MJWeakSelf
                    [cell setTextChangeBlock:^(NSString *changeText) {
                        weakSelf.listModel.realName = changeText;
                    }];
                }else if(indexPath.row == 1){
                    //性别
                    cell.inputTextField.text = self.listModel.sex;
                    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                    cell.inputTextField.userInteractionEnabled = NO;
                    self.sexTextField = cell.inputTextField;

                }else if(indexPath.row == 2){
                    //年龄
                    self.ageTextField = cell.inputTextField;
                    self.ageTextField.delegate = self;
                    cell.inputTextField.text = self.listModel.age;
                    cell.inputTextField.keyboardType = UIKeyboardTypeNumberPad;
                    MJWeakSelf
                    [cell setTextChangeBlock:^(NSString *changeText) {
                        weakSelf.listModel.age = changeText;
                    }];
                }else if(indexPath.row == 3){
                    //电话号码
                    self.phoneTextField = cell.inputTextField;
                    cell.inputTextField.text = self.listModel.phone;
                    cell.inputTextField.keyboardType = UIKeyboardTypeNumberPad;
                    MJWeakSelf
                    [cell setTextChangeBlock:^(NSString *changeText) {
                        weakSelf.listModel.phone = changeText;
                    }];
                }else if(indexPath.row == 4){
                    //城市
                    
                    NSString *province = self.listModel.province.length ? self.listModel.province : @"";
                    NSString *city = self.listModel.city.length ? self.listModel.city : @"";
                    cell.inputTextField.text = [NSString stringWithFormat:@"%@ %@",province,city];
                    cell.inputTextField.userInteractionEnabled = NO;
                    self.cityTextField = cell.inputTextField;
                    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        

                }
                
            }else if (indexPath.section == 5){
                cell.inputTextField.textAlignment = NSTextAlignmentLeft;
                if (indexPath.row == 0) {
                    //过敏病史—药物
                    self.medicinalTextField = cell.inputTextField;
                    cell.inputTextField.text = self.listModel.partyExtrView.medicinal;
                    MJWeakSelf
                    [cell setTextChangeBlock:^(NSString *changeText) {
                        weakSelf.listModel.partyExtrView.medicinal = changeText;
                    }];
                }else if(indexPath.row == 1){
                    //过敏病史—食物
                    self.foodTextField = cell.inputTextField;
                    cell.inputTextField.text = self.listModel.partyExtrView.food;
                    MJWeakSelf
                    [cell setTextChangeBlock:^(NSString *changeText) {
                        weakSelf.listModel.partyExtrView.food = changeText;
                    }];
                }
            }
            
            return cell;
        }

        //既往病史和生理状况
    }else if(indexPath.section == 2 || indexPath.section == 3){
        
        XMUserDetailInfoMultiSelectTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMUserDetailInfoMultiSelectTableViewCell className]];
        
        if (!cell) {
            cell = [[XMUserDetailInfoMultiSelectTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMUserDetailInfoMultiSelectTableViewCell className]];
        }
        
        if (indexPath.section == 2) {
            cell.tagList = self.listModel.partyExtrView.medicalHistoryView;
        }else{
            cell.tagList = self.listModel.partyExtrView.physiologicalConditionView;

        }
        
        return cell;
        
        //医美史
    }else if(indexPath.section == 4){
        
        //有医美史 material position project extr
        if (self.SurgeryDetailArr||self.listModel.partyExtrView.hasSurgeryDetail) {
            
            
            XMSurgeryDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMSurgeryDetailTableViewCell className]];
            
            if (!cell) {
                cell = [[XMSurgeryDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMSurgeryDetailTableViewCell className]];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            [cell.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(cell.contentView);
                make.height.equalTo(@0);
                
            }];
            cell.timeLabel.hidden = YES;
            cell.remarkTextView.userInteractionEnabled = NO;
            cell.remarkPlaceHolder.hidden = YES;
            cell.partLabel.text = @"部位:";
            cell.surgetyTypeLabel.text = @"项目位置:";
            cell.materialsLabel.text = @"材料:";
            cell.remarkTextView.text = self.listModel.partyExtrView.remark;
            
            if (self.SurgeryDetailArr.count>0) {
                //设置列表
                for (XMTypeListClassifyModel * thridModel in self.SurgeryDetailArr) {
                    if (thridModel.isSelected) {
                        cell.partLabel.text = [NSString stringWithFormat:@"%@ %@",cell.partLabel.text,thridModel.name];
                    }
                    
                    for (XMTypeListClassifyModel * fourthModel in thridModel.cateViews) {
                        if (fourthModel.isSelected) {
                            cell.surgetyTypeLabel.text = [NSString stringWithFormat:@"%@ %@",cell.surgetyTypeLabel.text,fourthModel.name];
                        }
                        
                        for (XMTypeListClassifyModel * fifthModel in fourthModel.cateViews) {
                            if (fifthModel.isSelected) {
                                cell.materialsLabel.text = [NSString stringWithFormat:@"%@ %@",cell.materialsLabel.text,fifthModel.name];
                            }
                        }
                    }
                }
            }else if (self.listModel.partyExtrView.hasSurgeryDetail){

                cell.partLabel.text = [NSString stringWithFormat:@"部位: %@",self.listModel.partyExtrView.position];
                cell.surgetyTypeLabel.text = [NSString stringWithFormat:@"项目位置: %@",self.listModel.partyExtrView.project];
                cell.materialsLabel.text = [NSString stringWithFormat:@"材料: %@",self.listModel.partyExtrView.material];
            }
            
            
            return cell;
            
        }else{
            //无医美史
            KTiltleAndInputTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[KTiltleAndInputTableViewCell className]];
            cell.inputTextField.textAlignment = NSTextAlignmentLeft;
            if (!cell) {
                cell = [[KTiltleAndInputTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[KTiltleAndInputTableViewCell className]];
            }
            
            cell.titleLabel.text = titleStr;
            cell.inputTextField.placeholder = placeHolderStr;
            cell.inputTextField.userInteractionEnabled = NO;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            cell.inputTextField.text = nil;
            
            return cell;
            
            
        }
        
        //备注
    }else{
        NSString * reuserId = @"xmremark";
        XMRemarkTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserId];
        
        if (!cell) {
            cell = [[XMRemarkTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserId];
        }
        cell.remarkTextView.text = self.listModel.partyExtrView.extr;

        cell.placeHolderLabel.text = @"输入其他备注";
        cell.remarkTextView.textColor = kTextGrayColor;
        self.remarkTextView = cell.remarkTextView;
        if (self.listModel.partyExtrView.extr.length>0) {
            cell.placeHolderLabel.hidden = YES;
        }else{
            cell.placeHolderLabel.hidden = NO;
        }
        MJWeakSelf
        [cell setTextChangeBlock:^(NSString *text) {
            weakSelf.listModel.partyExtrView.extr = text;

        }];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        [self p_showAddHeadImage];
    }else if (indexPath.section == 1&& indexPath.row == 1) {
        
        //性别
        [self p_showSexPicker];
    }else if (indexPath.section == 1 && indexPath.row ==4){
        //城市
        [self p_showLocationList];
    }else if (indexPath.section == 4) {
        XMTypeListViewController * vc  = [[XMTypeListViewController alloc]init];
        vc.type = 2;
        MJWeakSelf
        [vc setCallbackBlock:^(NSArray *selectedItemList,NSString * remark) {
            weakSelf.listModel.partyExtrView.remark = remark;
            NSArray *extractedExpr = selectedItemList;
            weakSelf.SurgeryDetailArr = extractedExpr;
            [weakSelf.tableView reloadSection:4 withRowAnimation:UITableViewRowAnimationNone];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark  ----netWork
-(void)getUserDetail{
    [self.view endEditing:YES];
    [KLProgressHUD showWaitingHUD];
    MJWeakSelf
    [AppNetwork album_V2GetPersonDetailInfoWithPartyId:self.partyId Completion:^(BOOL success, XMNewPersonDetailModel *model, AppError *error) {
        
        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            
            weakSelf.listModel = model;
            [weakSelf.tableView reloadData];
        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
    
}

//修改用户
-(void)uploadUserDetail{
    [self.view endEditing:YES];
    XMUserCreateModel * model = [[XMUserCreateModel alloc]init];
    model.addr = self.listModel.addr;
    if (self.listModel.age.length != 0) {
        
        if (self.listModel.age.length !=4 || (![[self.listModel.age substringWithRange:NSMakeRange(0,2)] isEqualToString:@"19"]&&![[self.listModel.age substringWithRange:NSMakeRange(0,2)] isEqualToString:@"20"])) {
            [KLProgressHUD showErrorHUDWithMessage:@"请输入正确年份 如1970"];
            return;
        }
    }
    
    model.age =self.listModel.age;
    model.city = self.listModel.city;
    model.province = self.listModel.province;
    model.extr = self.listModel.partyExtrView.extr;
    model.food = self.listModel.partyExtrView.food;
    model.medicinal = self.listModel.partyExtrView.medicinal;
    model.profile = self.listModel.profile;
    model.realName = self.listModel.realName;
    model.sex = self.listModel.sex;
    model.phone = self.listModel.phone;

    model.partyId = self.partyId;
    model.remark = self.listModel.partyExtrView.remark;
    if (self.SurgeryDetailArr.count>0) {
        NSMutableArray * thridIdsArr = [NSMutableArray array];
        NSMutableArray * fourthIdsArr = [NSMutableArray array];
        NSMutableArray * fifthIdsArr = [NSMutableArray array];
        
        for (XMTypeListClassifyModel * thirdmodel in self.SurgeryDetailArr) {
            if (thirdmodel.isSelected) {
                [thridIdsArr addObject:thirdmodel.id];
            }
            
            for (XMTypeListClassifyModel * fourthModel in thirdmodel.cateViews) {
                if (fourthModel.isSelected) {
                    [fourthIdsArr addObject:fourthModel.id];
                }
                
                
                for (XMTypeListClassifyModel * fifthModel in fourthModel.cateViews) {
                    if (fifthModel.isSelected) {
                        [fifthIdsArr addObject:fifthModel.id];
                    }
                }
            }
        }
        model.position = [thridIdsArr componentsJoinedByString:@","];
        model.project = [fourthIdsArr componentsJoinedByString:@","];
        model.material = [fifthIdsArr componentsJoinedByString:@","];
    }else if (self.listModel.partyExtrView.hasSurgeryDetail){
        
        model.position = self.listModel.partyExtrView.positionId;
        model.project = self.listModel.partyExtrView.projectId;
        model.material = self.listModel.partyExtrView.materialId;
    }
    
    NSMutableArray * physiologicalArr = [NSMutableArray array];
    
    for (XMUserDetailTagModel * physiologicalModel in self.listModel.partyExtrView.physiologicalConditionView) {
        if (physiologicalModel.isSelected) {
            [physiologicalArr addObject:physiologicalModel.id];
        }
    }
    
    NSMutableArray * medicalHisArr = [NSMutableArray array];
    
    for (XMUserDetailTagModel * medicalModel in self.listModel.partyExtrView.medicalHistoryView) {
        if (medicalModel.isSelected) {
            [medicalHisArr addObject:medicalModel.id];
            
        }
    }
    model.medicalHistory = [medicalHisArr componentsJoinedByString:@","];
    model.physiologicalCondition = [physiologicalArr componentsJoinedByString:@","];
    
    [KLProgressHUD showWaitingHUD];
    MJWeakSelf
    [AppNetwork album_V2uploadPersonDetailInfoWithCreateModel:model Completion:^(BOOL success, XMNewPersonDetailModel *model, AppError *error) {
        
        
        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            
            if (weakSelf.reloadBlock) {
                weakSelf.reloadBlock();
            }
            [KLProgressHUD showSuccessHUDWithMessage:@"修改成功"];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
        }
    }];
}

//删除用户
-(void)deleteUserDetail{
    
    [XMTitleAlterView showTypeMaterialListWithTitle:@"是否删除" sureBlock:^{
        [KLProgressHUD showWaitingHUD];
        [AppNetwork album_V2deletePersonDetailInfoWithPartyId:self.partyId doctorId:[LoginInfoModel getLoginInfo].id Completion:^(BOOL success, XMNewPersonDetailModel *model, AppError *error) {
            
            MJWeakSelf
            [KLProgressHUD hideHUDWithAnimated:YES];
            if (success) {
                if (weakSelf.reloadBlock) {
                    weakSelf.reloadBlock();
                }
                [KLProgressHUD showSuccessHUDWithMessage:@"删除成功"];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else{
                [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
            }
        }];
        
    } cancelBlock:^{
        
    }];


    
}

-(void)setPartyId:(NSString *)partyId{
    _partyId = partyId;
}


#pragma mark ----othter
//展示性别
- (void)p_showSexPicker {
    WEAKSELF
    [BRStringPickerView showStringPickerWithTitle:nil dataSource:kSexArray defaultSelValue:self.sexTextField.text resultBlock:^(id selectValue) {
        
        if ([NSString app_isBlankString:weakSelf.sexTextField.text] && [NSString app_isBlankString:selectValue]) {
            weakSelf.sexTextField.text = kSexArray[0];
            weakSelf.listModel.sex =kSexArray[0];
        }else {
            weakSelf.sexTextField.text = selectValue;
            weakSelf.listModel.sex =selectValue;

        }
    }];
}

//选择地区
- (void)p_showLocationList {
    AddressProvinceCityController *address = [[AddressProvinceCityController alloc] initWithAddressVCType:AddressVCTypeProvince parentId:@"" titleName:@""];
    [self.navigationController pushViewController:address animated:YES];
    
    WEAKSELF
    [address setAddressCompleted:^(NSString *province, NSString *city) {
        weakSelf.cityTextField.text = [NSString stringWithFormat:@"%@ %@", province, city];
        weakSelf.province = province;
        weakSelf.city = city;
        weakSelf.listModel.city = city;
        weakSelf.listModel.province = province;
    }];
}





- (void)p_showAddHeadImage {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择相片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    
    [actionSheet showInView:self.view];
}

#pragma mark - Request
- (void)request_uploadHeadImageWithImage:(UIImage *)image{
    WEAKSELF
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"上传头像.."];
    [AppHttpClient userModule_uploadImage:image completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
        progressHUD.hidden = YES;
        if (success) {
            weakSelf.listModel.profile = imageUrl;
            [weakSelf.tableView reloadSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }else {
            [KLProgressHUD showErrorHUDWithMessage:errorMsg];
        }
    }];
}

#pragma mark ----uitextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSCharacterSet *cs;
    if(textField == self.ageTextField)
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
            [KLProgressHUD showErrorHUDWithMessage:@"只能输入数字"];
            //输入了非法字符
            return NO;
        }
    }
    
    //其他的类型不需要检测，直接写入
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (self.ageTextField  == textField) {
        self.listModel.age = textField.text;
    }else if (self.medicinalTextField == textField){
        self.listModel.partyExtrView.medicinal = textField.text;
    }
}



#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) { // 打开相机
        if (![AppGlobal isCameraDeviceAvalable]) {
            
            UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }
        
        if (!self.imagePicker) {
            self.imagePicker = [[UIImagePickerController alloc]init];
        }
        
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.allowsEditing = NO;
        
        self.imagePicker.showsCameraControls = YES;
        self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
        self.imagePicker.mediaTypes = @[(NSString*)kUTTypeImage];
        [self presentViewController:self.imagePicker animated:YES completion:nil];
        
    } else if (1 == buttonIndex) { // 打开照片库
        if (![AppGlobal isAssetsLibraryAvalable]) {
            return;
        }
        [self selectPhotoToUpload];
        
    }
}


#pragma mark ----TZImagePicker----
//从相册中选取
-(void)selectPhotoToUpload{
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil ];
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowCrop = YES;
    
    //裁剪图片VC设置
    NSInteger width = kScreenWidth;
    NSInteger height = kScreenWidth;
    NSInteger top = (kScreenHeight-height)/2;
    imagePickerVC.cropRect = CGRectMake(0, top, width, height);
    
    
    MJWeakSelf
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count>0) {

            [weakSelf request_uploadHeadImageWithImage:photos[0]];

        }
    }];
    [self presentViewController:imagePickerVC animated:YES completion:nil];
    
}

#pragma mark - KGetImageDelegate


//获取图片信息
- (void)reloadPhotoArrayImage:(UIImage *)image {
    MJWeakSelf
    //获取相册最新的图片信息 也就是刚刚拍照保存的
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    PHAsset *phasset = [assetsFetchResults lastObject];
    
    [MBProgressHUD hideHUDWithAnimated:YES];
    //裁剪图片VC
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc]initCropTypeWithAsset:phasset photo:image completion:^(UIImage *cropImage, id asset) {
        [weakSelf request_uploadHeadImageWithImage:cropImage];
        
    }];
    //裁剪图片VC设置
    NSInteger width = kScreenWidth;
    NSInteger height = kScreenWidth;
    NSInteger top = (kScreenHeight-height)/2;
    imagePickerVC.cropRect = CGRectMake(0, top, width, height);
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowCrop = YES;
    
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count>0) {
            [weakSelf request_uploadHeadImageWithImage:photos[0]];
        }
    }];
    [self presentViewController:imagePickerVC animated:YES completion:nil];
    
}


#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *  image = info[UIImagePickerControllerOriginalImage];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        if (![self isCanUsePhotos]) {
            [KLProgressHUD showErrorHUDWithMessage:@"需要保存到相册权限"];
            return;
        }
        
        if (image) {
            //保存图片
            [[TZImageManager manager] savePhotoWithImage:image completion:^(NSError *error){
                if (!error) {
                    [self reloadPhotoArrayImage:image];
                }
            }];
        }
    }];
    
    
}

//判断是否有相册权限
- (BOOL)isCanUsePhotos {
    
    
    PHAuthorizationStatus photoAuthorStatus = [PHPhotoLibrary authorizationStatus];
    if (photoAuthorStatus == kCLAuthorizationStatusRestricted || photoAuthorStatus ==kCLAuthorizationStatusDenied){
        return NO;
    }else if (photoAuthorStatus == kCLAuthorizationStatusNotDetermined){
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            
        }];
    }
    
    
    return YES;
}

#pragma mark ---alterViewDelegate
-(void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
